package org.example.bean;//package org.example.bean;
//
//import okhttp3.OkHttpClient;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.core.env.Environment;
//import org.springframework.http.MediaType;
//import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
//import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
//import org.springframework.web.client.RestTemplate;
//
//import javax.net.ssl.*;
//import java.io.IOException;
//import java.io.InputStream;
//import java.nio.file.Files;
//import java.nio.file.Paths;
//import java.security.*;
//import java.security.cert.CertificateException;
//import java.util.Arrays;
//import java.util.concurrent.TimeUnit;
//
//
//@Configuration
//public class RestTemplateBeanWithCert {
//    private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateBeanWithCert.class);
//    private static final String CONNECT_TIMEOUT = "ok-http.connect-timeout";
//    private static final String READ_TIMEOUT = "ok-http.read-timeout";
//    private static final String WRITE_TIMEOUT = "ok-http.write-timeout";
//    private static final String TRUST_STORE = "naie.trust-store";
//    private static final String KEY_STORE = "naie.key-store";
//    private static final String KEY_PASSWORD = "naie.key-password";
//    @Autowired
//    private Environment env;
//
//    /**
//     * 注入restTemplate
//     *
//     * @return restTemplate
//     */
//    @Bean(name = "restTemplate")
//    public RestTemplate restTemplate() {
//        // 证书校验
//        TrustManager[] trustManagers = getTrustManagers();
//        KeyManager[] keyManagers = getKeyManagers();
//        // 自定义ssl上下文
//        SSLSocketFactory sslSocketFactory = getSSLSocketFactory(keyManagers, trustManagers);
//        // 自定义域名校验
//        HostnameVerifier verifier = getHostnameVerifier();
//        // 构造okHttpClient
//        String connectTimeout = env.getProperty(CONNECT_TIMEOUT, "60");
//        String readTimeout = env.getProperty(READ_TIMEOUT, "10");
//        String writeTimeout = env.getProperty(WRITE_TIMEOUT, "6");
//        OkHttpClient client = new OkHttpClient.Builder().hostnameVerifier(verifier)
//                // ssl配置
//                .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustManagers[0])
//                .connectTimeout(Long.parseLong(connectTimeout), TimeUnit.SECONDS)
//                .readTimeout(Long.parseLong(readTimeout), TimeUnit.SECONDS)
//                .writeTimeout(Long.parseLong(writeTimeout), TimeUnit.SECONDS).build();
//
//        OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(client);
//        // 构造restTemplate
//        RestTemplate restTemplate = new RestTemplate(factory);
//        // 兼容TEXT_PLAIN, 有些接口返回是这种奇怪的类型
//        MappingJackson2HttpMessageConverter textConverter = new MappingJackson2HttpMessageConverter();
//        textConverter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_HTML, MediaType.TEXT_PLAIN));
//        restTemplate.getMessageConverters().add(textConverter);
//
//        return restTemplate;
//    }
//
//    private HostnameVerifier getHostnameVerifier() {
//        return new HostnameVerifier() {
//            @Override
//            public boolean verify(String hostname, SSLSession session) {
//                // TODO: 主机名认证规则
//                return true;
//            }
//        };
//    }
//
//    private TrustManager[] getTrustManagers() {
//        String trustKeyStore = String.format("%s/%s", IOUtil.getRootPath(), env.getProperty(TRUST_STORE));
//
//        TrustManager[] trustManagers = null;
//        try (InputStream ipts = Files.newInputStream(Paths.get(trustKeyStore))) {
//            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
//            KeyStore tks = KeyStore.getInstance("JKS");
//            tks.load(ipts, null);
//            trustManagerFactory.init(tks);
//            trustManagers = trustManagerFactory.getTrustManagers();
//        } catch (IOException e) {
//            LOGGER.error("unable to load server public key cert.", e);
//            throw new CertAccessException(e);
//        } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException e) {
//            LOGGER.error("unable to build trustManagers.", e);
//            throw new GenericSslException(e);
//        }
//
//        return trustManagers;
//    }
//
//    private KeyManager[] getKeyManagers() {
//        String keyStore = String.format("%s/%s", IOUtil.getRootPath(), env.getProperty(KEY_STORE));
//        String keyPassword = env.getProperty(KEY_PASSWORD);
//        // 如果运行本地测试就不解密了，因为证书和密码固定
//        if (!StringUtils.isBlank(keyPassword) && StringUtils.startsWith(keyPassword, "security:")) {
//            keyPassword = CryptoUtil.decrypt(env.getProperty(KEY_PASSWORD));
//        } else {
//            keyPassword = env.getProperty(KEY_PASSWORD);
//        }
//
//        KeyManager[] keyManagers = null;
//        try (InputStream ipts = Files.newInputStream(Paths.get(keyStore))) {
//            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
//            KeyStore ks = KeyStore.getInstance("PKCS12");
//            //加载证书
//            ks.load(ipts, keyPassword.toCharArray());
//            keyManagerFactory.init(ks, keyPassword.toCharArray());
//            keyManagers = keyManagerFactory.getKeyManagers();
//        } catch (IOException e) {
//            LOGGER.error("unable to load client private key cert.", e);
//            throw new CertAccessException(e);
//        } catch (UnrecoverableKeyException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
//            LOGGER.error("unable to build keyManagers.", e);
//            throw new GenericSslException(e);
//        }
//
//        return keyManagers;
//    }
//
//    private SSLSocketFactory getSSLSocketFactory(KeyManager[] keyManagers, TrustManager[] trustManagers) {
//        try {
//            // 信任任何链接
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(keyManagers, trustManagers, null);
//            return sslContext.getSocketFactory();
//        } catch (NoSuchAlgorithmException | KeyManagementException e) {
//            LOGGER.error("create ssl socket factory failed.", e);
//            throw new GenericSslException(e);
//        }
//    }
//}
